/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.IOException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 *
 * @author aisyah
 */
public class RMSCounter {

    RecordStore rStore;
    String rmsName = "counter";

    public void open() {
        try {
            rStore = RecordStore.openRecordStore(rmsName, true);
            System.out.println("Open RMS");
            System.out.println("Size " + rStore.getSize());
            System.out.println("Size avalilabe " + rStore.getSizeAvailable());
        } catch (RecordStoreException recordstoreexception) {
            recordstoreexception.printStackTrace();
        }
    }

    public void close() {
        try {
            rStore.closeRecordStore();
            System.out.println("Close RMS");
        } catch (RecordStoreNotOpenException recordstorenotopenexception) {
            recordstorenotopenexception.printStackTrace();
        } catch (RecordStoreException recordstoreexception) {
            recordstoreexception.printStackTrace();
        }
    }

    public boolean isEmpty() {

        try {
            System.out.println("Num record : " + rStore.getNumRecords());
            if (rStore.getNumRecords() < 1) {
                return true;
            } else {
                return false;
            }
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
            return true;
        }
    }

    public void updateRecord(int index, String str) {
        byte[] rec = str.getBytes();

        try {
            rStore.setRecord(index, rec, 0, rec.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int readRecords(int index) {
        int result = 0;
        try {
            byte[] recData = new byte[10];
            int len;
            // Re-allocate if necessary
            if (rStore.getRecordSize(index) > recData.length) {
                recData = new byte[rStore.getRecordSize(index)];
            }
            len = rStore.getRecord(index, recData, 0);
            result = Integer.parseInt(new String(recData, 0, len));
            System.out.println("Record #" + index + ": " + result);

        } catch (Exception e) {

            System.out.print("Defaul value " + result);
        }
        return result;
    }

    public void writeRecord(String str) {
        byte[] rec = str.getBytes();

        try {
            rStore.addRecord(rec, 0, rec.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
